package cloud.forms;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import cloud.beans.Anime;
import cloud.dao.AnimeDao;

public final class AnimeForm extends Form{

	private static final String CHAMP_NAME = "name";
	private static final String CHAMP_SYNOPSIS = "synopsis";
	private static final String CHAMP_IMAGEPATH = "pathImg";

	private AnimeDao animeDao;
	private Anime anime;
	
	public AnimeForm() {
		
		super();
		this.animeDao = new AnimeDao();
		this.anime = new Anime();
	}
	
	
	public Anime createAnime( HttpServletRequest request ) {
	
		String name = getValeurChamp( request, CHAMP_NAME );
		String synopsis = getValeurChamp( request, CHAMP_SYNOPSIS );
		String pathImg = getValeurChamp( request, CHAMP_IMAGEPATH );
		
		try {
			validationChampRequis(name);
		}
		catch ( Exception e ) {
			setErreur( CHAMP_NAME, e.getMessage() );
		}
		this.anime.setName( name );
	
		try {
			validationChampRequis(synopsis);
		}
		catch ( Exception e ) {
			setErreur( CHAMP_SYNOPSIS, e.getMessage() );
		}
		this.anime.setSynopsis(synopsis);
		this.anime.setPathImg(pathImg);
			
		if ( this.erreurs.isEmpty() ) {
			if (this.animeDao.creer(this.anime))
				resultat = "Success.";
			else {
				setErreur(null, "Error.");
				this.resultat = "Technical error.";
			}
		} 
		else {
			this.resultat = "Error.";
		}
		
		

		return this.anime;
	}
	
	public List<Anime> getList(){

		// Récuperation de la liste des codes en fonction de la rubrique
		List<Anime> animeList = animeDao.lister();

		// Si la recherche retourne un resultat
		if ( animeList != null && !animeList.isEmpty() ) {
			resultat = "Liste récupérée.";
		}
		
		return animeList;
	}
	
	public Anime getAnimeById( long id ){

		// Récuperation de la liste des codes en fonction de la rubrique
		Anime anime = animeDao.trouver( id );

		// Si la recherche retourne un resultat
		if ( anime != null ) {
			resultat = "Entrée récupérée.";
		}
		
		return anime;
	}
}